package com.project.personalfundmanager.client.taxitems;

import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.project.personalfundmanager.client.common.UIHelper;

public abstract class ParentItem<D extends BaseModel> extends ContentPanel
{
	protected UIHelper uiHelper = new UIHelper( this );
	private FormPanel formPanel;
	private FormPanel totalPanel;
	public D model;
	private boolean nonZeroMode;

	public ParentItem( D model )
	{
		setHeaderVisible( false );
		
		addFormPanel();
		addTotalPanel();

		FormBinding binding = new FormBinding( formPanel );
		FormBinding binding2 = new FormBinding( totalPanel );

		binding.autoBind();
		binding.bind( model );

		binding2.autoBind();
		binding2.bind( model );

		this.model = model;
	}

	protected void addFormPanel()
	{
		formPanel = new FormPanel();
		formPanel.setLabelWidth( 200 );
		formPanel.setHeaderVisible( false );
		addFormComponents( formPanel, true );
		add( formPanel );
	}

	protected void addTotalPanel()
	{
		totalPanel = new FormPanel();
		totalPanel.setLabelWidth( 100 );
		totalPanel.setHeaderVisible( false );
		addTotalComponents( totalPanel );
		add( totalPanel );
	}

	public void clearItems()
	{
		for ( String propertyName : model.getPropertyNames() )
		{
			model.set( propertyName, null );
		}
	}

	public void setNonZeroMode( boolean b )
	{
		this.nonZeroMode = b;
	}
	
	void addToPanel( ContentPanel panel, Field< ? > widget )
	{
		if ( !nonZeroMode )
			panel.add( widget );
		else
		{
			Object value = model.get( widget.getName() );
			if ( value != null || ( value instanceof Number && !value.equals( 0 ) ) )
				panel.add( widget );
		}
	}

	public abstract void addFormComponents( FormPanel formPanel, boolean isEditable );

	public abstract void addTotalComponents( FormPanel totalPanel );

	public abstract void calculateTotal();

}
